#!/usr/bin/env node
var express = require('express');

var https = require('https');
var BodyParser = require('body-parser');
var path = require('path');
var config = require('./config');
const AIService = require('./AIAnalyze');

var app = express();

var URI = require('./UriConst');

// 创建服务器
var apps = https.createServer(
    config.https,
    app
);
app.use('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header(
        'Access-Control-Allow-Headers',
        'Content-Type,Content-Length, Authorization, Accept,X-Requested-With'
    );
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
    if (req.method === 'OPTIONS') {
        res.send(200);
    } else {
        next();
    }
});

app.use(BodyParser.json());

app.use(express.static(path.join(__dirname, 'dist')));

let notifyListener = null;
function onNotify(req) {
    if (null == req) {
        return;
    }
    let params = req.body;
    if (null == params) {
        return;
    }
    console.error(JSON.stringify(req.body));
    let action = params.action;
    if (null == action) {
        return;
    }
    if (notifyListener != null) {
        notifyListener.onNotify(action, params.app, params.params);
    }
}

app.post(URI.notify, (req, res) => {
    onNotify(req);
    res.send(200);
});

aiService = null;
app.get(URI.getCameras, (req, res) => {
    console.info("server getCameras begin");
    if (null == aiService) {
        res.json({result: 'failed', error:'ai service not exist'});
        return;
    }
    var analyzes = aiService.getAnalyzes();
    if (null == analyzes) {
        res.json({result: 'failed',error:'get cameras null'});
        return;
    }
    var arr = [];
    analyzes.forEach((analyze, id) => {
        console.error(JSON.stringify(analyze) + ";id:" + id + "\r\n");
        arr.push(analyze);
    });
    res.json({result: 'success',
        data:arr
    });
});

// 不拒绝未认证的证书
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

let port = config.port;
apps.listen(port, (error) => {
    AIService.setCSVPath(path.join(__dirname, 'cameras.csv'));
    aiService = new AIService(config.api, config.appkey);
    aiService.subScribeNotify(config.httpsUri + URI.notify);
    notifyListener = aiService;
    if (error != null) {
        console.log(error);
    }
    console.log('The HTTPS server is up and running at port ' + port);
});
